<template>
  <div id="firmOrder">
    <header>
      <i @click="goBack()"></i>
      <div>确认订单</div>
    </header>
    <div class="box1">
      <div class="box">
        <div class="top"></div>
        <div class="bottom">
          <div class="left">
            <img :src="img_url" width="86" height="110" />
            <span>
              <div>{{name}}</div>
              <div>￥{{cost_price}}</div>
            </span>
          </div>
          <div class="right">
            <span @click="minus">-</span>
            <span>{{goodsnum<10?'0':''}} {{goodsnum}} </span> <span @click="add">+</span>
          </div>
        </div>
      </div>
      <router-link class="address" :to="{name:'selectAddress'}" v-show='!defaultAddress'>
        <div>
          <img src="../../image/address1.png" alt="">
          添加收货地址
        </div>
        <img src="../../image/icon_gray_next.png" alt="">
      </router-link>
      <router-link class="address1" :to="{name:'selectAddress'}" v-show='defaultAddress'>
        <div class="left">
          <div><img src="../../image/address2.png" alt=""></div>
          <div><img src="../../image/address3.png" alt=""></div>
          <div><img src="../../image/address4.png" alt=""></div>
        </div>
        <div class=right>
          <div style="color:rgba(0, 0, 0, 0.75);font-size: 13px">{{defaultAddress.name}}</div>
          <div>{{defaultAddress.phone}}</div>
          <div>{{defaultAddress.selectCity + defaultAddress.detailAddress}}</div>
        </div>
      </router-link>
      <div class="need">
        <img src="../../image/title.png" alt="">

        <textarea placeholder="给卖家留言你的需求" v-model="need"></textarea>
      </div>
      <div class="border-8"></div>
      <div class="payType">
        <label @change="select">
          <img src="../../image/icon_zhifubao_pay.png" width="33" height="33" alt="">
          支付宝支付
          <input type="radio" value="支付宝" v-model="payType">
          <i></i>
        </label>
        <label @change="select">
          <img src="../../image/icon_weixin_pay.png" width="33" height="33" alt="">
          微信支付
          <input type="radio" value="微信" v-model="payType">
          <i></i>
        </label>
        <a class="moreType" @click="morePay">更多支付方式选择 <img src="../../image/row-bottom.jpg" width="20" alt=""></a>
      </div>

      <div class="submitOrder">
        合计:<span>￥<i>{{totalPrice}}</i></span>
        <a class="submitBtn" @click='submitOrder'>提交订单</a>
      </div>
    </div>


  </div>
</template>
<script>
  export default {
    data() {
      return {
        aaa: '',
        defaultAddress: '', //默认收货地址
        payType: '支付宝',
        img_url: '', //商品图片
        goodsnum: '1', //商品数量
        cost_price: '', //单价
        name: '', //商品名
        need: '', //需求
        userid: '',
        goodsid: '',
        selectGoods: {}, //选中商品的规格颜色数量
        orderList: [], //选中商品的详细信息(名字 图片)
        totalPrice: '', //合计价格
      }
    },
    components: {

    },
    methods: {
      goBack() {
        this.$router.back();
      },
      add() {
        this.goodsnum++
        this.goodsnum = this.goodsnum
        this.totalPrice = this.goodsnum * this.cost_price
      },
      minus() {
        if (this.goodsnum < 2) {} else {
          this.goodsnum--
        }
        this.goodsnum = this.goodsnum
        this.totalPrice = this.goodsnum * this.cost_price
      },
      // 支付宝付款
      pay_zhifubao(obj) {
        const data = {
          order_num: obj.order_num,
          subject: '团购订单',
          amount: this.totalPrice,
        };
        this.$api.post(this.$api.baseURL2, "/alipay_app", data, r => {
            var params = r.data.data;
            cordova.plugins.alipay.payment(params, function () {
              this.$utils._toast('支付成功');
            }, function (reason) {
              this.$utils._toast(reason);
            });
          }, err => {
            console.log(err);
          }, false, false)
      },
      // 微信支付
      pay_wx(obj) {
        const data = {
          order_num: obj.order_num,
          total_fee: this.totalPrice,
          des: '团购订单'
        };
        this.$api.post(this.$api.baseURL2, "/android_wxpay", data, r => {
          var params = {
            partnerid: r.data.mch_id, // merchant id 
            prepayid: r.data.prepay_id, // prepay id 
            noncestr: r.data.nonce_str, // nonce 
            timestamp: r.data.timestamp, // timestamp 
            sign: r.data.sign, // signed string 
          };
          Wechat.sendPaymentRequest(params, function () {
            this.$utils._toast('支付成功');
          }, function (reason) {
            this.$utils._toast(reason);
          });
        }, err => {
          console.log(err);
        }, false, false)
        // const data = {
        //   order_num: obj.order_num,
        //   body: this.orderList[0].name,
        //   total_fee: this.totalPrice,
        // };
        // console.log(data);
        // this.$api.post(this.$api.baseURL, "wx_h5pay2", data, r => {
        //   console.log(r);
        //   // alert(JSON.stringify(r));
        //   window.location.href = res.data.mweb_url;
        // }, err => {
        //   console.log(err);
        // }, false, false)
      },
      // 支付
      goPay(data) {
        if (this.payType == '支付宝') {
          this.pay_zhifubao(data);
        } else if (this.payType == '微信') {
          this.pay_wx(data);
          //   this.$utils._toast("暂不支持")
        }
      },
      //提交订单
      submitOrder() {
        var addarr = [];
        var that = this;
        this.orderList.forEach(function (item, index) {
          addarr.push({
            gid: item.gid || that.goodsid,
            num: item.num,
            standard: item.standard,
          });
        });
        var data = {};
        data.address = JSON.stringify(this.defaultAddress);
        if (!this.defaultAddress) {
          this.$utils._toast('请选择收货地址');
          return false;
        }
        data.cash_fee = this.totalPrice;
        data.gids = JSON.stringify(this.orderList);
        data.need = this.need; //需求
        data.cost_price = this.cost_price; //单价
        data.goodsnum = this.goodsnum; //数量
        data.uid = this.userid;
        console.log(data); //gids可以改成商品描述
        this.$api.post(this.$api.baseURLSchool, "update_order/add", data, r => {
          if (r.data.ret == 1) { //提交订单成功
            //提交后删除购物车
            var that = this;
            this.orderList.forEach(function (item, index) {
              const params = {
                id: item.cid
              }
              that.$api.post(that.$api.baseURLSchool, "dataupdate/carts/del", params, r => {
                // console.log(r);

              }, err => {
                console.log(err);
              })
            });
            // 去支付
            this.goPay(r.data);
          }
        }, err => {
          console.log(err);
        })

      },
      //多选框change事件
      select() {
        console.log(this.payType);
      },
      //获取默认地址 最新添加的地址
      getDefaultAddress() {
        this.userid = localStorage.getItem("loginMobile");
        this.$api.get(this.$api.baseURLSchool, "selectdata2/user_relative?user_id=" + this.userid + "&type=address", {},
          r => {
            console.log(r);
            //如果有选择地址就显示选择的
            if (localStorage.getItem("selectAddress")) {
              this.defaultAddress = JSON.parse(localStorage.getItem("selectAddress"));
            } else if (r.data.ret == 1) { //否则显示最新添加的地址
              if (r.data.info.length > 0) { //否则显示最新添加的地址
                this.defaultAddress = JSON.parse(r.data.info[0].content);
              }
            } else {
              this.defaultAddress = '';
            }
            // console.log(this.defaultAddress);
          }, err => {
            console.log(err);
          })
      },
      morePay() {
        this.$utils._toast("暂不支持其他方式");
      },
      //获取订单列表商品详情
      getDetailsData() {
        //判断入口
        //商品详情
        if (this.$route.query.id) {
          this.goodsid = this.$route.query.id;
          this.$api.get(this.$api.baseURLSchool, "selectdetail/goods/" + this.goodsid, {}, r => {
            console.log('***', );


            this.name = r.data.info.name
            this.cost_price = r.data.info.cost_price
            this.img_url = r.data.info.img_url
            this.$set(this.orderList, 0, r.data.info);
            this.orderList[0].standard = localStorage.getItem("selectGoods");
            this.orderList[0].num = JSON.parse(localStorage.getItem("selectGoods")).num;
            console.log(this.orderList);
            var that = this;
            this.orderList.forEach(function (item, index) {
              that.totalPrice += (item.cost_price * item.num);
            });
          }, err => {
            console.log(err);
          })
          //如果是从详情页过来就用local存储的规格颜色
          this.getSelectGoods();
        } else if (this.$route.query.cartsList) { //购物车
          this.orderList = JSON.parse(this.$route.query.cartsList);
          // console.log(this.orderList);
          var that = this;
          this.totalPrice = 0;
          this.orderList.forEach(function (item, index) {
            that.totalPrice += (item.cost_price * item.num);
          });
        } else if (this.$route.query.orderList) { //订单管理
          const orderList = [];
          orderList.push(JSON.parse(this.$route.query.orderList));
          console.log(orderList);
          this.orderList = orderList;
          this.orderList.forEach((item, index) => {
            this.totalPrice += (item.cost_price * item.num);
          });
        } else {

        }

      },
      //获取用户选择的商品规格颜色
      getSelectGoods() {
        // this.goodsid = this.$route.query.id;
        this.selectGoods = JSON.parse(localStorage.getItem("selectGoods"));
      },
    },
    created() {
      this.getDetailsData();
      this.getDefaultAddress();
    },
    mounted() {

    }
  }

</script>
<style lang="scss">
</style>
